package com.cogent.validator.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import com.cogent.common.util.Globals;
import com.cogent.common.util.StringUtil;
import com.cogent.common.util.XmlUtil;
import com.cogent.validator.domain.ValidatorDomain;

public class ValidatorXmlParse {
	public static String VALIDATOR_RULE_FILE = Globals.getRootPath() + "WEB-INF/config/validator-rules.xml";
	public static List parseXml(String formName) {
		List list = new ArrayList();
		Document doc = XmlUtil.loadXmlFormFile(VALIDATOR_RULE_FILE);
		Node node = doc.selectSingleNode("//root/form[@name='" + formName + "']");
		if(node != null) {
			List nodeList = node.selectNodes("field");
			Iterator it = nodeList.iterator();
			while(it.hasNext()) {
				Element e = (Element)it.next();
				String key = XmlUtil.getAttributeValue(e, "key");
				String property = XmlUtil.getAttributeValue(e, "property");
				String depends = XmlUtil.getAttributeValue(e, "depends");
				if(!StringUtil.isEmpty(depends)) {
					ValidatorDomain validatorDomain = new ValidatorDomain();
					validatorDomain.setKey(key);
					validatorDomain.setProperty(property);
					validatorDomain.setValidator(depends);
					validatorDomain.setNotemsg(XmlUtil.getAttributeValue(e, "notemsg"));
					validatorDomain.setKeypairmap(stringToMap(XmlUtil.getAttributeValue(e, "varinfo")));
					list.add(validatorDomain);
				}
				List itemList = e.selectNodes("item");
				if((itemList != null) && (itemList.size()>0)) {
					Iterator it2 = itemList.iterator();
					while(it2.hasNext()) {
						Element e2 = (Element)it2.next();
						ValidatorDomain validatorDomain = new ValidatorDomain();
						validatorDomain.setKey(key);
						validatorDomain.setProperty(property);
						validatorDomain.setValidator(XmlUtil.getAttributeValue(e2, "depends"));
						validatorDomain.setNotemsg(XmlUtil.getAttributeValue(e2, "notemsg"));
						validatorDomain.setKeypairmap(stringToMap(XmlUtil.getAttributeValue(e2, "varinfo")));
						list.add(validatorDomain);
					}
				}
			}
		}
		
		return list;
	}
	
	public static HashMap stringToMap(String str) {
		HashMap retMap = null;
		if(!StringUtil.isEmpty(str)) {
			retMap = new HashMap();
			String[] temps = str.split(";");
			for(int i=0; i<temps.length; i++) {
				String[] curtemps = temps[i].split("\\|");
				retMap.put(curtemps[0], curtemps[1]);
			}
		}
		return retMap;
	}
}
